<template>
  <div class="update-name">
    <!-- 导航栏 -->
    <van-nav-bar
      left-text="取消"
      right-text="完成"
      title="修改昵称"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
    <!-- /导航栏 -->

    <van-field
      v-model="newName"
      type="textarea"
      maxlength="7"
      placeholder="请输入新昵称"
      show-word-limit
    />
  </div>
</template>

<script>
import { updateUserProfile } from "@/api/user";

export default {
  name: "UpdateName",
  props: ["value"],
  data() {
    return {
      newName: this.value, // 输入的新昵称
    };
  },
  methods: {
    // 点击完成
    async onConfirm() {
      const newName = this.newName.trim();

      if (!newName) return this.$toast.fail("昵称不能为空");
      if (newName === this.value) return this.$emit("close");

      this.$toast.loading({
        message: "保存中...",
        forbidClick: true,
      });

      try {
        await updateUserProfile({
          name: newName,
        });
        this.$toast.success("保存成功");
        this.$emit("input", newName);
        this.$emit("close");
      } catch (err) {
        this.$toast.fail("保存失败");
      }
    },
  },
};
</script>

<style scoped lang="less">
.van-popup {
  background-color: #f5f7f9;
}

/deep/.van-nav-bar__text {
  color: #fff;
}

.van-field {
  margin-top: 10px;
}
</style>
